package cn.com.ghy.android.widget.salemag;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.YGOrderInfoBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.YgOrderOpeService;
import cn.com.ghy.android.style.CustomProgressDialog;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

public class SaleManageOrder extends Activity {

	private ImageButton btnQuery;
	private ImageButton btnAddOrder;

	private Button btnStartDate;
	private Button btnEndDate;

	private TextView txtOrderNum;

	private LinearLayout linHint;
	private ListView listData;

	private ProgressDialog progressDialog;
	private Bundle bundle;
	private Intent intent;

	private LoginInfoBean loginInfo;
	private String startDateStr;
	private String endDateStr;
	private String orderid;
	private Map<String, Object> map = new HashMap<String, Object>();
	private List<YGOrderInfoBean> list = new ArrayList<YGOrderInfoBean>();

	private HttpThread httpThread;

	private DisposeException disposeException;
	private Exception error;

	private int mYear = 0, mMonth = 0, mDay = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sale_manager_order);
		getSession();
		findView();
		init();
		addListener();
	}

	public void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) this.getApplication()).getLoginInfo();
	}

	private void findView() {
		btnQuery = (ImageButton) findViewById(R.id.btnQuery);
		btnAddOrder = (ImageButton) findViewById(R.id.btnAddOrder);

		btnStartDate = (Button) findViewById(R.id.btnStartDate);
		btnEndDate = (Button) findViewById(R.id.btnEndDate);

		txtOrderNum = (TextView) findViewById(R.id.txtOrderNum);

		linHint = (LinearLayout) findViewById(R.id.linHint);
		listData = (ListView) findViewById(R.id.listData);
	}

	private void init() {
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
	}

	private void addListener() {
		btnQuery.setOnClickListener(btnListener);
		btnAddOrder.setOnClickListener(btnListener);

		btnStartDate.setOnClickListener(btnListener);
		btnEndDate.setOnClickListener(btnListener);

		listData.setOnItemClickListener(new OrderDataLisEvent());
	}

	private View.OnClickListener btnListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btnQuery :
					startDateStr = (String) btnStartDate.getText().toString();
					endDateStr = (String) btnEndDate.getText().toString();
					if ("开始日期".equals(startDateStr)) {
						Toast.makeText(SaleManageOrder.this, "请选择查询开始日期", //
								Toast.LENGTH_SHORT).show();
						break;
					}
					if ("结束日期".equals(endDateStr)) {
						Toast.makeText(SaleManageOrder.this, "请选择查询结束日期", //
								Toast.LENGTH_SHORT).show();
						break;
					}

					if (!CommonUtil.checkDate(SaleManageOrder.this, //
							startDateStr.trim() + " 00:00:00", //
							endDateStr.trim() + " 23:59:59")) {
						break;
					}

					operate(R.id.btnQuery);
					break;
				case R.id.btnAddOrder :
					operate(R.id.btnAddOrder);
					break;
				case R.id.btnStartDate :
					showDialog(R.id.btnStartDate);
					break;
				case R.id.btnEndDate :
					showDialog(R.id.btnEndDate);
					break;
				default :
					break;
			}
		}

	};

	private class OrderDataLisEvent implements AdapterView.OnItemClickListener {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			YGOrderDataListAdapter yGOrderDataListAdapter = (YGOrderDataListAdapter) (parent
					.getAdapter());
			showAlertDialog(SaleManageOrder.this, position,
					yGOrderDataListAdapter.getItem(position));

		}
	}

	private void operate(int opcode) {
		progressDialog = new CustomProgressDialog(SaleManageOrder.this);
		progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				httpThread.stopSendMsg();
			}
		});
		progressDialog.show();

		httpThread = new HttpThread(opcode);
		Thread thread = new Thread(httpThread);
		thread.start();
	}

	private void showAlertDialog(final Context context, final int position, //
			final YGOrderInfoBean bean) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("提示信息:");
		builder.setMessage("订单编号：" + bean.getOrderid());
		builder.setPositiveButton("查看", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				orderid = bean.getOrderid();
				operate(CommonStatic.STATE_SEE);
			}
		});
		if (bean.getState().equals("未处理")) {
			builder.setNegativeButton("修改", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					orderid = bean.getOrderid();
					operate(CommonStatic.STATE_MOD);
				}
			});
		}
		builder.show();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final int btnId = id;
		DatePickerDialog datePickerDialog = new DatePickerDialog(this, //
				new DatePickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						String date = CommonUtil.formateDate(year, monthOfYear, dayOfMonth);
						switch (btnId) {
							case R.id.btnStartDate :
								btnStartDate.setText(date);
								break;
							case R.id.btnEndDate :
								btnEndDate.setText(date);
								break;
							default :
								break;
						}

					}

				}, mYear, mMonth, mDay);
		return datePickerDialog;
	}

	private class HttpThread implements Runnable {

		private int opcode;

		public HttpThread(int opcode) {
			this.opcode = opcode;
		}

		private boolean isSendMsg = true;

		@Override
		public void run() {
			Message message = handler.obtainMessage();
			YgOrderOpeService service = new YgOrderOpeService();
			try {
				switch (opcode) {
					case R.id.btnQuery :
						list = service.GetOrderList("", startDateStr, //
								endDateStr, loginInfo);
						break;
					case R.id.btnAddOrder :
						map = service.GetInitOrder(loginInfo);
						break;
					case CommonStatic.STATE_SEE :
					case CommonStatic.STATE_MOD :
						map = service.OrderShow(orderid);
						break;
					default :
						break;
				}
			} catch (Exception e) {
				opcode = CommonStatic.ERROR_CODE;
				error = e;
			}
			if (isSendMsg) {
				message.what = opcode;
				handler.sendMessage(message);
			}
		}

		public void stopSendMsg() {
			isSendMsg = false;
		}

		@SuppressWarnings("unused")
		public void openSendMsg() {
			isSendMsg = true;
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
				case R.id.btnQuery :
					YGOrderDataListAdapter yGOrderDataListAdapter = new YGOrderDataListAdapter(
							SaleManageOrder.this, list);
					listData.setAdapter(yGOrderDataListAdapter);
					txtOrderNum.setText(yGOrderDataListAdapter.getCount() + "");
					linHint.setVisibility(View.GONE);
					listData.setVisibility(View.VISIBLE);
					break;
				case R.id.btnAddOrder :
					bundle = new Bundle();
					bundle.putInt("intentFlag", CommonStatic.STATE_ADD);
					bundle.putSerializable("order", (Serializable) map);
					intent = new Intent(SaleManageOrder.this, SaleOrder.class);
					intent.putExtras(bundle);
					SaleManageOrder.this.startActivity(intent);
					break;
				case CommonStatic.STATE_SEE :
					bundle = new Bundle();
					bundle.putSerializable("order", (Serializable) map);
					intent = new Intent(SaleManageOrder.this, SaleOrderView.class);
					intent.putExtras(bundle);
					SaleManageOrder.this.startActivity(intent);
					break;
				case CommonStatic.STATE_MOD :
					bundle = new Bundle();
					bundle.putString("orderid", orderid);
					bundle.putInt("intentFlag", CommonStatic.STATE_MOD);
					bundle.putSerializable("order", (Serializable) map);
					intent = new Intent(SaleManageOrder.this, SaleOrder.class);
					intent.putExtras(bundle);
					SaleManageOrder.this.startActivity(intent);
					break;
				case CommonStatic.ERROR_CODE :
					disposeException.handleException(error);
					break;
				default :
					break;
			}
		}
	};

	private class YGOrderDataListAdapter extends BaseAdapter {

		private Context context = null;
		private List<YGOrderInfoBean> list = new ArrayList<YGOrderInfoBean>();

		public YGOrderDataListAdapter(Context context, List<YGOrderInfoBean> list) {
			this.context = context;
			this.list = list;
		}

		public int getCount() {
			return list.size();
		}

		public YGOrderInfoBean getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(inflater);
			LinearLayout linearLayout = null;
			YGOrderInfoBean bean = list.get(position);
			linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.sale_manager_order_lay,
					null);
			TextView textView = ((TextView) linearLayout.findViewById(R.id.labOrderNo));
			textView.setText((position + 1) + ".订单编号:");

			textView = ((TextView) linearLayout.findViewById(R.id.orderNo));
			textView.setText(bean.getOrderid());

			textView = ((TextView) linearLayout.findViewById(R.id.status));
			textView.setText(bean.getState());

			textView = ((TextView) linearLayout.findViewById(R.id.sendGoodsDate));
			textView.setText(bean.getCdate());

			textView = ((TextView) linearLayout.findViewById(R.id.address));
			textView.setText(bean.getStrasno());

			return linearLayout;
		}

	}
}
